package org.example.aitest.test;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import okhttp3.*;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.entity.mime.*;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.message.BasicHeader;
import org.apache.hc.core5.util.Timeout;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.example.aitest.utils.HttpClientUploader;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.MultipartBodyBuilder;
import org.springframework.http.codec.multipart.FilePart;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClientResponseException;
import reactor.core.publisher.Mono;

import java.io.*;
import java.util.*;
import java.util.concurrent.TimeUnit;

public class QwenLong {

    private static final Integer TIME_OUT= 5 * 60;

    static final OkHttpClient client = new OkHttpClient().newBuilder()
            .connectTimeout(TIME_OUT, TimeUnit.SECONDS)
            .readTimeout(TIME_OUT,TimeUnit.SECONDS)
            .writeTimeout(TIME_OUT,TimeUnit.SECONDS)
            .build();

//    public static void main(String[] args) throws IOException {
//
//        String fileId = getFileId();
//        MediaType mediaType = MediaType.parse("application/json");
//
//        String content = "{\"model\":\"qwen-long\",\"messages\":[" +
//                "{\"role\":\"system\",\"content\":\"You are a helpful assistant.\"}," +
//                "{\"role\":\"system\",\"content\":\"fileid://"+fileId+"\"}," +
//                "{\"role\":\"user\",\"content\":\"公司有多少人\"}" +
//                "]," +
//                "\"stream\":true," +
//                "\"stream_options\":{\"include_usage\":true}}";
//        RequestBody body = RequestBody.create(mediaType, content);
//
//        Request request = new Request.Builder()
//                .url("https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions")
//                .post(body)
//                .addHeader("Content-Type", "application/json")
//                .addHeader("Authorization", "Bearer sk-06daae4607c0459295ccd4db313f9719")
//                .build();
//        Response execute = client.newCall(request).execute();
//        StringBuilder builder = new StringBuilder();
//        if(execute.isSuccessful()){
//            ResponseBody body1 = execute.body();
//            if (body1 != null) {
//                // 使用ResponseBody的source()方法以流的方式处理响应
//                try (BufferedReader reader = new BufferedReader(new InputStreamReader(body1.byteStream()))) {
//                    String line;
//                    while ((line = reader.readLine()) != null) {
//                        // 处理每一行数据
//                        if(line.length() > 15) {
//                            String substring = line.substring(5);
//                            JSONObject jsonObject = JSONObject.parseObject(substring);
//                            JSONArray choices = jsonObject.getJSONArray("choices");
//                            if(!choices.isEmpty()) {
//                                JSONObject jsonObject1 = (JSONObject) choices.get(0);
//                                JSONObject jsonObject2 = (JSONObject) jsonObject1.get("delta");
//                                String content1 = (String) jsonObject2.get("content");
//                                builder.append(content1);
//                            }
//                        }
//                    }
//                    System.out.println(builder);
//                }
//            }
//        }
//
////        Generation gen = new Generation();
////
////        GenerationParam param = GenerationParam.builder()
////                .apiKey("sk-06daae4607c0459295ccd4db313f9719")
////                .model("Qwen-Long")
////                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
////                .build();
//    }

    public static void main(String[] args) throws IOException {
        getFileId();
    }

    private static void getFileId() throws IOException {
      /*  File file = new File("C:\\Users\\Admin\\Desktop\\公司基本信息.txt");
        MediaType mediaType = MediaType.parse("application/octet-stream");
        RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("purpose","file-extract")
                .addFormDataPart("file", file.getName(),
                        RequestBody.create(mediaType,file))
                .build();

        Request request = new Request.Builder()
                .url("https://dashscope.aliyuncs.com/compatible-mode/v1/files")
                .post(body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Authorization", "Bearer sk-06daae4607c0459295ccd4db313f9719")
                .build();
        Response execute = client.newCall(request).execute();
        JSONObject jsonObject = JSONObject.parseObject(execute.body().string());
        String fileId = (String) jsonObject.get("id");
        System.out.println("文件id"+fileId);*/

        String uploadUrl = "https://dashscope.aliyuncs.com/compatible-mode/v1/files";

        // 准备文件
        Map<String, File> files = new HashMap<>();
        files.put("file", new File("C:\\Users\\Admin\\Desktop\\公司基本信息.txt"));

        // 准备其他参数
        Map<String, String> params = new HashMap<>();
        params.put("purpose", "file-extract");
//        params.put("description", "测试文件上传");

        try {
            String response = HttpClientUploader.upload(uploadUrl, files, params);
            System.out.println("上传结果: " + response);
        } catch (IOException e) {
            e.printStackTrace();
        }

        /*File file = new File("C:\\Users\\Admin\\Desktop\\公司基本信息.txt");
        String url = "https://dashscope.aliyuncs.com/compatible-mode/v1/files";

        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        headers.set("Authorization","Bearer sk-06daae4607c0459295ccd4db313f9719");

        MultiValueMap<String,Object> body = new LinkedMultiValueMap<>();
        body.add("file",new FileSystemResource(file));
        body.set("purpose","file-extract");

        HttpEntity<MultiValueMap<String,Object>> requestEntity = new HttpEntity<>(body,headers);
        ResponseEntity<String> response = restTemplate.postForEntity(url,requestEntity,String.class);
        System.out.println(response.getBody());*/

       /* String url = "https://dashscope.aliyuncs.com/compatible-mode/v1/files";

        WebClient webClient = WebClient
                .builder()
                .defaultHeader("Authorization","Bearer sk-06daae4607c0459295ccd4db313f9719")
                .build();

        MultipartBodyBuilder builder = new MultipartBodyBuilder();
        builder.part("file",new FileSystemResource("C:\\Users\\Admin\\Desktop\\公司基本信息.txt"));
        builder.part("purpose","file-extract");

        Mono<String> stringMono = webClient.post()
                .uri(url)
                .contentType(MediaType.MULTIPART_FORM_DATA)
                .body(BodyInserters.fromMultipartData(builder.build()))
                .retrieve()
                .bodyToMono(String.class)
                .doOnError(e -> System.out.println("上传失败" + e.getMessage()))
                .onErrorResume(WebClientResponseException.class, ex ->
                    Mono.just("服务器错误："+ex.getMessage())
                )
                .onErrorResume(IOException.class,e -> Mono.just("读取文件失败"))
                .onErrorResume(e -> Mono.just("上传失败"));
        System.out.println(stringMono.flux().blockFirst());*/

    }
}
